package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private WorkSpaceService workSpaceService;

    /**
     * 功能描述: 营业额统计
     * 无间隔显示
     *
     * @return : java.lang.Object
     */
    @Override
    public TurnoverReportVO getTurnover(String begin, String end) {
        //1.根据开始时间，结束时间，封装日期列表 dateList
        List<LocalDate> dateList = new ArrayList<>();
        LocalDate beginDate = LocalDate.parse(begin, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate endDate = LocalDate.parse(end, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        dateList.add(beginDate);
        while (!(beginDate.equals(endDate))) {
            beginDate = beginDate.plusDays(1);
            dateList.add(beginDate);
        }
       /*使用日期类型接收
       LocalDate begin, LocalDate end
       List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);//日期计算，获得指定日期后1天的日期
            dateList.add(begin);
        }

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin", beginTime);
            map.put("end", endTime);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        //数据封装
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();*/
        ArrayList<BigDecimal> turnoverList = new ArrayList<>();
        List<LocalDate> localDates = orderMapper.turnoverStatisticsDate(begin, end, 5);
        List<BigDecimal> actAmountList = orderMapper.turnoverStatisticsAmount(begin, end, 5);
        //2.1遍历全部日期
        for (int i = 0; i < dateList.size(); i++) {
            //获取全部日期中，当前遍历的日志
            LocalDate currentDate = dateList.get(i); //13
            //获取索引值
            int index = localDates.indexOf(currentDate);
            if (index < 0) {
                turnoverList.add(new BigDecimal(0));
                continue;
            }
            //有数据，把日期数据添加13号数据 244.00 0 25.00 205 0 0
            turnoverList.add(actAmountList.get(index));
        }
        //3.日期、数据，封装成字符串进行返回
        String dateListStr = "";
        String turnoverListStr = "";
        for (int i = 0; i < dateList.size(); i++) {
            LocalDate localDate = dateList.get(i);
            String localDateStr = localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            if (i == dateList.size() - 1) {
                dateListStr += localDateStr;
            } else {
                dateListStr += localDateStr + ",";
            }
        }
        for (int i = 0; i < turnoverList.size(); i++) {
            String amount = turnoverList.get(i).toString();
            if (i == turnoverList.size() - 1) {
                turnoverListStr += amount;
            } else {
                turnoverListStr += amount + ",";
            }
        }
        return new TurnoverReportVO().builder().dateList(dateListStr).turnoverList(turnoverListStr).build();
    }

    /**
     * 功能描述: 图形化数据，有日期间隔数据展示
     * 营业额统计
     *
     * @param begin 开始时间
     * @param end   结束时间
     * @return : com.sky.vo.TurnoverReportVO
     */
    /*public TurnoverReportVO getTurnover(String begin, String end) {
        List<LocalDate> dateList = orderMapper.turnoverStatisticsDate(begin, end, 5);
        List<BigDecimal> amountList = orderMapper.turnoverStatisticsAmount(begin, end, 5);
        //遍历数据，封装keys和values
        String dateListStr = "";
        String turnoverList = "";
        for (int i = 0; i < dateList.size(); i++) {
            LocalDate localDate = dateList.get(i);
            String localDateStr = localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            if (i == dateList.size() - 1) {
                dateListStr += localDateStr;
            } else {
                dateListStr += localDateStr + ",";
            }
        }
        for (int i = 0; i < amountList.size(); i++) {
            String amount = amountList.get(i).toString();
            if (i == amountList.size() - 1) {
                turnoverList += amount;
            } else {
                turnoverList += amount + ",";
            }
        }
        return new TurnoverReportVO().builder().dateList(dateListStr).turnoverList(turnoverList).build();
    }*/


    /**
     * 功能描述: 用户数据统计
     *
     * @return : com.sky.vo.UserReportVO
     */

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> dateArrayList = new ArrayList<>();
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateArrayList.add(begin);
        }

        //新增用户
        ArrayList<Integer> newList = new ArrayList<>();
        //总用户
        ArrayList<Integer> allList = new ArrayList<>();

        for (LocalDate date : dateArrayList) {
            //取出开始和结束时间
            LocalDateTime beginDate = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endDate = LocalDateTime.of(date, LocalTime.MAX);
            //通过时间计算新增用户和总用户
            Integer newUser = getUserCount(beginDate, endDate);
            Integer allUser = getUserCount(null, endDate);
            newList.add(newUser);
            allList.add(allUser);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateArrayList, ","))
                .newUserList(StringUtils.join(newList, ","))
                .totalUserList(StringUtils.join(allList, ","))
                .build();
    }

    /**
     * 根据时间区间统计用户数量
     *
     * @param beginTime
     * @param endTime
     * @return
     */
    public Integer getUserCount(LocalDateTime beginTime, LocalDateTime endTime) {
        Map map = new HashMap();
        map.put("begin", beginTime);
        map.put("end", endTime);
        return userMapper.countByMap(map);
    }

    /**
     * 功能描述: 订单统计
     *
     * @return : com.sky.vo.OrderReportVO
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //计算日期集合
        ArrayList<LocalDate> localDateArrayList = new ArrayList<>();
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            localDateArrayList.add(begin);
        }
        //每天的订单数
        ArrayList<Integer> orderNumList = new ArrayList<>();
        //每天有效订单数
        ArrayList<Integer> validOrderNumList = new ArrayList<>();
        for (LocalDate date : localDateArrayList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询每天的订单总数
            Integer orderCount = getOrderCount(beginTime, endTime, null);
            //查询每天有效订单数
            Integer orderCount1 = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            orderNumList.add(orderCount);
            validOrderNumList.add(orderCount1);
        }
        //时间区间内总订单数
        Integer totalOrderCount = orderNumList.stream().reduce(Integer::sum).get();
        //时间区间内有效订单数
        Integer validOrderCount = validOrderNumList.stream().reduce(Integer::sum).get();
        //订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        return OrderReportVO.builder().dateList(StringUtils.join(localDateArrayList, ","))
                .orderCountList(StringUtils.join(orderNumList, ","))
                .validOrderCountList(StringUtils.join(validOrderNumList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate).build();
    }

    /**
     * 根据时间区间统计指定状态的订单数量
     *
     * @param beginTime
     * @param endTime
     * @param status
     * @return
     */
    private Integer getOrderCount(LocalDateTime beginTime, LocalDateTime endTime, Integer status) {
        Map map = new HashMap();
        map.put("status", status);
        map.put("begin", beginTime);
        map.put("end", endTime);
        return orderMapper.countByMap(map);
    }

    /**
     * 功能描述: 销量排名
     *
     * @return : com.sky.vo.SalesTop10ReportVO
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(beginTime, endTime);

        String nameList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()), ",");
        String numberList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()), ",");

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 功能描述: 数据导出
     *
     * @return : void
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {

        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        //查询概览运营数据，提供给Excel模板文件
        BusinessDataVO businessData = workSpaceService.businessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        System.out.println(businessData);
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于提供好的模板文件创建一个新的Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //获得Excel文件中的一个Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            //获取单元格
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //准备明细数据
                businessData = workSpaceService.businessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.flush();
            out.close();
            excel.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
